package com.musemun.config.handler;

import com.alibaba.fastjson.JSON;
import com.musemun.common.CommonResult;
import com.musemun.config.Listener.ExcelListener;
import com.musemun.pojo.Employee;
import com.musemun.pojo.EmployeeRepository;
import com.musemun.service.EmployeeService;
import com.musemun.service.function.functionimpl.EmployeeDetailService;
import com.musemun.util.JwtTokenUtil;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    Logger log = LoggerFactory.getLogger(LoginSuccessHandler.class);
    @Resource
    EmployeeDetailService employeeDetailService;

    @Resource
    EmployeeRepository employeeRepository;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        final Employee employee = (Employee) employeeDetailService.loadUserByUsername(authentication.getName());
        log.info("登入保存开始");
        final String token = JwtTokenUtil.generateToken(employee);
        employeeRepository.insert(employee);

        returnToken(httpServletResponse,token);
    }
    public void returnToken(HttpServletResponse response,String token) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        CommonResult<Map<String, String>> mapCommonResult = new CommonResult<>(200,"登入成功",map);
        writer.write(JSON.toJSONString(mapCommonResult));
        writer.flush();
    }
}
